# -*- coding:utf8 -*-
"""
本地存储
"""
from __future__ import print_function, unicode_literals
import os
import codecs
from json import loads, dumps


class Cache(object):
    """
    本地cache
    """
    pass


class CacheWithFile(object):
    """
    采用文件使用的cache
    """

    def __init__(self, file_path):
        self.value_path = file_path + '.cache'
        if os.path.exists(self.value_path):
            self.dict_ = self.load_cache()
        else:
            self.dict_ = {}
        self.fo = codecs.open(self.value_path, 'w', encoding='utf8')

    def load_cache(self):
        dict_ = {}
        with codecs.open(self.value_path, encoding='utf8') as fi:
            for line in fi:
                key, value = loads(line)
                dict_[key] = value
        return dict_

    def save(self, key, value):
        dump_str = dumps((key, value))
        self.fo.write(dump_str)
        self.fo.write('\n')
        return True

    def get(self, key):
        value = self.dict_.get(Key)
        return value

